
package server;

import SBLib.User;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *  Class with static methods that provide server the ability to manage files on disk.
 * 
 * @author BrandonNeal
 */
public class FileIO 
{
    public static String USER_DIR = "Users/";
    public static String FILE_DIR = "Files/";
    
    public static void SaveFile(String fileName, String content)
    {
        FileWriter fstream = null;
        try 
        {
            fstream = new FileWriter(fileName);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(content);
            out.close();
        }
        catch (IOException ex) 
        {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } 
        finally 
        {
            try {
                fstream.close();
            } catch (IOException ex) {
                Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public static String[] GetFiles(String directory)
    {
        File dir = new File(directory);
        String[] filenames = dir.list();
        return filenames;
    }
    public static String GetFileContent(String fileName)
    {
        BufferedInputStream f = null;
        String content = "";
        try
        {
            byte[] buffer = new byte[(int) new File(fileName).length()];
            f = new BufferedInputStream(new FileInputStream(fileName));
            f.read(buffer);
            content = new String(buffer);
        } 
        catch (IOException ex) 
        {
            Logger.getLogger(FileIO.class.getName()).log(Level.SEVERE, null, ex);
        } 
        finally 
        {
            try
            {
                f.close();
            } 
            catch (IOException ex)
            {
                Logger.getLogger(FileIO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        return content;
          
    }
    public static void DeleteFile(String file)
    {
        File f=new File(file);
        if(f.exists() && f.isFile())
        {
            f.delete();
        }
    }
    public static void RenameFile(String fileName, String newFileName)
    {
        File f = new File(fileName);
        File renamed = new File(newFileName);
        
        if(f.exists() && f.isFile())
        {
            f.renameTo(renamed);
        }
    }
    public static void EditFile(String fileName, String content)
    {
        //TODO. Server Deletes and then makes a new file for now.
    }
}
